package com.southwind.springboottest.study.Java中通讯;



import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;


public class SerialCommunication {

    public static void main(String[] args) {
        try {
            Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
            CommPortIdentifier portId = null;
            while (portList.hasMoreElements()) {
                CommPortIdentifier id = portList.nextElement();
                if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    portId = id;
                    break;
                }
            }

            if (portId != null) {
                SerialPort serialPort = (SerialPort) portId.open("SerialCommunication", 2000);
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                // 发送数据
                out.write("AT\r".getBytes());

                // 读取数据
                byte[] buffer = new byte[1024];
                int len = in.read(buffer);
                System.out.println("Received data: " + new String(buffer, 0, len));

                serialPort.close();
            } else {
                System.out.println("No serial port found.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


